package com.cardmanager.pro.business.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import com.cardmanager.pro.pojo.CreditCardAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cardmanager.pro.business.CreditCardManagerConfigBusiness;
import com.cardmanager.pro.pojo.CreditCardManagerConfig;
import com.cardmanager.pro.repository.CreditCardManagerConfigRepository;

@Service
public class CreditCardManagerConfigBusinessImpl implements CreditCardManagerConfigBusiness {

	@Autowired
	private CreditCardManagerConfigRepository creditCardManagerConfigRepository;
	
	@Autowired
	private EntityManager em;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	@Cacheable(value = "CreditCardManagerConfig",keyGenerator="keyGenerator")
	public CreditCardManagerConfig findByChannelType(String channelType) {
		return creditCardManagerConfigRepository.findByChannelType(channelType);
	}

	@Transactional
	@Override
	@CachePut(value = "CreditCardManagerConfig", key = "#model.brandId +':'+ #model.channelType")
	public CreditCardManagerConfig save(CreditCardManagerConfig model) {
		model = creditCardManagerConfigRepository.save(model);
		em.flush();
		em.close();
		return model;
	}

	@Override
	@Cacheable(value = "CreditCardManagerConfig",keyGenerator="keyGenerator")
	public List<CreditCardManagerConfig> findByBrandId(String brandId) {
		return creditCardManagerConfigRepository.findByBrandId(brandId);
	}


	public List<CreditCardManagerConfig> findCreditCardManagerConfig (String brandId){
		String sql = "select * from t_credit_card_manager_config where brand_id = '" + brandId + "' " ;
		SqlRowSet set = jdbcTemplate.queryForRowSet(sql);
		List<CreditCardManagerConfig> list = new ArrayList<>();
		while (set.next()){
			CreditCardManagerConfig config = new CreditCardManagerConfig();
			config.setBrandId(set.getString("brand_id"));
			config.setChannelId(set.getString("channel_id"));
			config.setChannelTag(set.getString("channel_tag"));
			config.setChannelType(set.getString("channel_type"));
			config.setFirstMoney(set.getInt("first_money"));
			config.setSingleLimitCount(set.getInt("single_limit_count"));
			config.setSingleLimitMoney(set.getInt("single_limit_money"));
			list.add(config);
		}
		return list;
	}

	@Override
	@Cacheable(value = "CreditCardManagerConfig",key = "#brandId +':'+ #channelType")
	public CreditCardManagerConfig findByBrandIdAndChannelType(String brandId, String channelType) {
		return creditCardManagerConfigRepository.findByBrandIdAndChannelType(brandId,channelType);
	}
}
